package v1

import (
	"encoding/json"
	"net/http"
	"server/global/e"
	"server/global/response"
	"server/service"

	"github.com/gin-gonic/gin"
)

type emqxResForm struct {
	Code int `json:"code"`
	Data []struct {
		Clientid  string `json:"clientid"`
		Connected bool   `json:"connected"`
	} `json:"data"`
}

// @Summary Emqx Check Online
// @Produce  json
// @Success 200 {object} response.Response
// @Failure 500 {object} response.Response
// @Router /api/v1/emqx/check_online [get]
func EmqxCheckOnline(c *gin.Context) {
	r := response.Gin{C: c}
	res := service.EmqxGetClients()
	var emqx emqxResForm
	err := json.Unmarshal([]byte(res), &emqx)
	if err != nil {
		r.Response(http.StatusInternalServerError, e.ERROR_EMQX_GET_CLIENTS, nil)
		return
	}
	devices, _ := service.DeviceGetAll()
	for i := range devices {
		device := devices[i]
		device.Online = 0
		for j := range emqx.Data {
			if devices[i].Sn == emqx.Data[j].Clientid {
				device.Online = 1
				break
			}
		}
		service.DeviceEdit(*device)
	}

	r.Response(http.StatusOK, e.SUCCESS, emqx)
}
